//
//  UserAccount.swift
//  weibo
//
//  Created by yellow on 15/10/17.
//  Copyright © 2015年 yellow. All rights reserved.
//

import UIKit

/**
 ### 用户帐号模型
 #### 返回数据格式
 ``` json
    {
    "access_token": "ACCESS_TOKEN",
    "expires_in": 1234,
    "remind_in":"798114",
    "uid":"12341234"
    }
 ```
 [see api](http://open.weibo.com/wiki/OAuth2/access_token)
*/
class UserAccount: NSObject,NSCoding{

    //MARK: - 属性

 /// 用于调用access_token，接口获取授权后的access token
    var access_token:String?
 /// access_token的生命周期，单位是秒数,因为是基本数据类型需要赋初值，不然会找不到这个kvc属性
    var expires_in:NSTimeInterval = 0 {
        //属性检查器，当该属性被赋值后，执行didSet里面的代码
        didSet{
            self.availableDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
 /// 当前授权用户的UID
    var uid:String?
    init(dict:[String:AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    /// 根据expires_in计算出token的有效日期
    var availableDate:NSDate?
    
    ///用户昵称
    var screen_name:String?
    /// 用户头像地址（大图）
    var avatar_large:String?
    
    //MARK: - 方法
    
    //对于模型中不存在的key，不予处理
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    /// 打印模型的各个属性值
    override var description:String{
        let keys = ["access_token", "expires_in", "availableDate", "uid", "screen_name", "avatar_large"]
        return dictionaryWithValuesForKeys(keys).description
    }
    
    // MARK: - 归档解档需要实现的协议方法

    //归档
     func encodeWithCoder(aCoder: NSCoder){
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(availableDate, forKey: "availableDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        //因为expires_in没有时效性，只需要保存availableDate即可
     }
    
    //解档
     required init?(coder aDecoder: NSCoder){
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        availableDate = aDecoder.decodeObjectForKey("availableDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
     }
    
    
}
